import os
from datetime import datetime

class HTMLReporter:
    def __init__(self, logger, report_dir="./test_results/reports/"):
        self.logger = logger
        self.report_dir = os.path.abspath(report_dir)
        self.report_path = None

    def generate_report(self, summary_data, case_logs):
        """生成HTML报告"""
        try:
            # 确保报告目录存在, 不存在则创建目录
            os.makedirs(self.report_dir, exist_ok=True)
            self.report_path = os.path.join(
                self.report_dir,
                f"TestReport_{datetime.now().strftime('%Y%m%d%H%M%S')}.html"
            )
            report_data = self._prepare_report_data(summary_data, case_logs)
            html_content = self._build_html_template(report_data)
            with open(self.report_path, "w", encoding="utf-8") as f:
                f.write(html_content)
            self.logger.info(f"HTML测试报告已生成: {self.report_path}")
        except Exception as e:
            self.logger.error(f"生成HTML报告失败: {str(e)}")

    def _prepare_report_data(self, summary_data, case_logs):
        """准备报告数据"""
        start_times = [v.get('start_time', datetime.now()) for v in summary_data.values()]
        return {
                'start_time': min(start_times) if start_times else datetime.now(),
                'end_time': datetime.now(),
                'total_cases': sum([v['case_total'] for v in summary_data.values()]),
                'passed_cases': sum([v['case_pass'] for v in summary_data.values()]),
                'failed_cases': sum([v['case_fail'] for v in summary_data.values()]),
                'sheets': {
                    sheet: {
                        'cases': [case for case in case_logs if case['sheet'] == sheet],
                        'groups': list({case['group'] for case in case_logs if case['sheet'] == sheet})
                    }
                    for sheet in summary_data
                }
            }

    def _build_html_template(self, data):
        """生成HTML报告模版"""
        return f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>自动化测试报告</title>
            <style>
                body {{ font-family: Arial, sans-serif; margin: 20px; }}
                .summary {{ background: #f5f5f5; padding: 20px; border-radius: 5px; }}
                .stats {{ margin: 10px 0; }}
                .sheet-section {{ margin-top: 30px; border: 1px solid #ddd; padding: 15px; border-radius: 5px; }}
                .detail-table {{ width: 100%; border-collapse: collapse; margin-top: 10px; }}
                .detail-table th, .detail-table td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
                .pass {{ background-color: #dfffdf; color: #2a662a; }}
                .fail {{ background-color: #ffe5e5; color: #ff0000; }}
                .log-detail {{
                    display: none;
                    background: #f8f8f8;
                    padding: 10px;
                    margin: 5px 0;
                    border-radius: 3px;
                    white-space: pre-wrap;
                    font-family: Consolas, monospace;
                }}
                .step-row {{ cursor: pointer; }}
                .step-row:hover {{ background-color: #f0f0f0; }}
                h3 {{ color: #333; border-bottom: 2px solid #eee; padding-bottom: 5px; }}
            </style>
            <script>
                function toggleLog(logId) {{
                    const logElement = document.getElementById(logId);
                    logElement.style.display = logElement.style.display === 'none' ? 'block' : 'none';
                }}
            </script>
        </head>
        <body>
            <h1>自动化测试报告</h1>

            <div class="summary">
                <h2>测试概览</h2>
                <p>开始时间: {data['start_time'].strftime("%Y-%m-%d %H:%M:%S")}</p>
                <p>结束时间: {data['end_time'].strftime("%Y-%m-%d %H:%M:%S")}</p>
                <p>总耗时: {(data['end_time'] - data['start_time']).total_seconds():.2f}秒</p>
                <p>用例总数: {data['total_cases']} (通过: <span class="pass">{data["passed_cases"]}</span>, 失败: <span class="fail">{data["failed_cases"]}</span>)</p>
            </div>

            <h2>详细结果</h2>
            {self._generate_sheet_sections(data['sheets'])}
        </body>
        </html>
            """

    def _generate_sheet_sections(self, sheets_data):
        """生成Sheet部分的HTML内容"""
        sheet_sections = []
        for sheet_name, sheet_info in sheets_data.items():
            section = [
                f'<div class="sheet-section">',
                f'<h3>{sheet_name}</h3>',
                '<table class="detail-table">',
                '<thead><tr><th>分组</th><th>用例名称</th><th>状态</th><th>耗时</th><th>步骤详情</th></tr></thead>',
                '<tbody>'
            ]

            # 按分组归类用例
            groups = {}
            for case in sheet_info['cases']:
                group_name = case.get('group', '未分组')
                if group_name not in groups:
                    groups[group_name] = []
                groups[group_name].append(case)

            # 生成表格行
            for group_name, cases in groups.items():
                for case in cases:
                    # 步骤详情HTML
                    steps_html = ['<ul>']
                    for idx, step in enumerate(case['steps']):
                        actual_content = step.get("actual", "").replace("\n", "<br>")
                        steps_html.append(
                            f'<li class="step-row" onclick="toggleLog(\'log_{case["id"]}_{idx}\')">'
                            f'{step["step"]} - <span class="{step["status"]}">{step["status"].upper()}</span>'
                            f'<div id="log_{case["id"]}_{idx}" class="log-detail">{actual_content}</div>'
                            f'</li>'
                        )
                    steps_html.append('</ul>')

                    # 用例行
                    section.append(
                        f'<tr>'
                        f'<td>{group_name}</td>'
                        f'<td>{case["name"]}</td>'
                        f'<td class="{case["status"].lower()}">{case["status"]}</td>'
                        f'<td>{case["duration"]:.2f}s</td>'
                        f'<td>{"".join(steps_html)}</td>'
                        f'</tr>'
                    )

            section.extend(['</tbody></table></div>'])
            sheet_sections.append("".join(section))

        return "".join(sheet_sections)